<template>
    <div class="main">
      <p  class="main_text">司机管理</p>
        <!-- ############################################## 表单 ############################################## -->
        <div class="cyr-flex">
            <div class="mb20">
                <el-button type="primary" @click="centerDialogVisible = true" v-if='roleList.write'>添加司机</el-button>
            </div>
          <div class="cyr-flex-box">
            <el-table @selection-change="handleSelectionChange" :data="tableData"
                :header-cell-style="{ 'background': '#f0f6fe' }" border  v-adaptive   :show-overflow-tooltip="true">
                <el-table-column type="selection" width="50" />
                <el-table-column label="司机姓名" prop="name">
                    <template #default="props">
                        <el-text tag="span" style='cursor: pointer;' @click="check(props.row)">{{ props.row.name
                            }}</el-text>
                    </template>
                </el-table-column>
                <el-table-column label="司机账号" prop="phone" />
                <el-table-column label="司机联系方式" prop="phone" />
                <!-- status   1--在线   0--离线   2--托运中  -->
                <el-table-column label="状态">
                    <template #default="props">
                        <el-tag type="danger" v-if="props.row.status === 0">离线</el-tag>
                        <el-tag type="success" v-else-if="props.row.status === 1">在线</el-tag>
                        <el-tag type="warning" v-else-if="props.row.status === 3">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="添加时间" prop="createdAt" :show-overflow-tooltip="true" />
                <el-table-column label="操作">
                    <template #default="props">
                        <el-button size="small" link type="primary" @click="check(props.row)"
                            v-if="roleList.read">查看</el-button>
                        <el-button size="small" link type="danger" @click="delBtn(props.row)"
                            v-if="roleList.write">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="Number(total)"
                @change="handleCurrentChange" />
          </div>
        </div>
        <!-- ############################################## 蒙层 ############################################## -->
        <!-- ****************************** 添加司机 ****************************** -->
        <el-dialog class="dialog" v-model="centerDialogVisible" width="40%" align-center>
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">添加司机</p>
                </div>
            </template>
            <el-form ref="ruleFormRef" :model="addTableData" :rules="rules" label-width="6.25rem" label-position="left"
                class="df fdc aic">
                <el-form-item label="手机号码：" style="width: 70%;" prop="phone">
                    <el-input v-model="addTableData.phone" placeholder="手机号码：" />
                </el-form-item>
                <!-- 司机身份证 -->
                <el-form-item label="司机身份证:" style="width: 70%;">
                    <upload :limit="2" :multiple="false" :fileType="'image'" @changeFileList="hanldeIdCarImg"></upload>
                </el-form-item>
                <el-form-item label="司机姓名：" style="width: 70%;" prop="name">
                    <el-input v-model="addTableData.name" placeholder="司机姓名：" />
                </el-form-item>
                <el-form-item label="身份证号:" style="width: 70%;" prop="identityCard">
                    <el-input v-model="addTableData.identityCard" placeholder="司机身份证号：" />
                </el-form-item>
                <el-form-item label="性别：" style="width: 70%;" prop="gender">
                    <el-input v-model="addTableData.gender" placeholder="性别：" />
                </el-form-item>
                <!-- 驾照上传 -->
                <el-form-item label="电子驾照：" style="width: 70%;">
                    <upload :limit="1" :multiple="false" :fileType="'image'" @changeFileList="hanldeElectronIdCarImg">
                    </upload>
                </el-form-item>
                <el-form-item label="驾照编号：" style="width: 70%;">
                    <el-input v-model="addTableData.licenseNumber" placeholder="驾照编号：" />
                </el-form-item>
                <el-form-item label="驾照有效期：" style="width: 70%;">
                    <el-date-picker v-model="addTableData.limit" format="YYYY-MM-DD" type="date" style="width: 100%" />
                </el-form-item>
                <!-- <el-form-item label="初始密码：" style="width: 70%;">
                    <el-input v-model="addTableData.password" placeholder="初始密码：" />
                </el-form-item>
              <el-form-item label="隶属公司：" style="width: 70%;">
                    <el-select v-model="addTableData.affiliatedCompany" placeholder="隶属公司：">
                        <el-option label="Zone one" value="shanghai" />
                        <el-option label="Zone two" value="beijing" />
                    </el-select>
                </el-form-item> 
               <el-form-item label="备注：" style="width: 70%;">
                    <el-input v-model="addTableData.remarks" type="textarea" placeholder="司机姓名：" />
                </el-form-item> -->
            </el-form>
            <template #footer>
                <el-button @click="centerDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addDriverBtn(ruleFormRef)">确定</el-button>
            </template>
        </el-dialog>
        <!-- ****************************** 查看司机信息 ****************************** -->
        <el-dialog class="dialog" v-model="editcenterDialogVisible" width="40%" align-center>
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">查看司机信息</p>
                </div>
            </template>
            <el-form :model="checkTableData" label-width="5.125rem" label-position="left" class="df fdc aic">
                <el-form-item label="姓名：" style="width: 70%;">
                    <el-text>{{ checkTableData.name }}</el-text>
                </el-form-item>
                <el-form-item label="性别：" style="width: 70%;">
                    <el-text>{{ checkTableData.gender }}</el-text>
                </el-form-item>
                <el-form-item label="驾驶证：" style="width: 70%;">
                    <el-text>{{ checkTableData.licenseNumber }}</el-text>
                </el-form-item>
                <el-form-item label="电话：" style="width: 70%;">
                    <el-text>{{ checkTableData.phone }}</el-text>
                </el-form-item>
                <el-form-item label="身份证号：" style="width: 70%;">
                    <el-text>{{ checkTableData.identityCard }}</el-text>
                </el-form-item>
                <el-form-item label="身份证：" style="width: 70%;">
                    <template v-for="(item) in identityCardImg" :key="item.id">
                        <el-image style="width: 6.25rem; height: 6.25rem;margin-right: 1rem;" :src="item.url"
                            fit="contain" :preview-src-list="srcList"></el-image>
                    </template>
                </el-form-item>
                <el-form-item label="驾照：" style="width: 70%;">
                    <el-image style="width: 6.25rem; height: 6.25rem" :src="licenseNumberImg" fit="contain" />
                </el-form-item>
                <el-alert v-if="switchStatus === 3" title="资料有误，请重新上传" type="error" :closable="false" />
            </el-form>
            <template #footer>
                <el-button @click="editcenterDialogVisible = false">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { RequestTransportDriversGetlistlimit, RequestBasicDrivingLicense, RequestAddDriver, RequestChangeDriverStatus, RequestTransportDriversUploadDriverInfo, RequestTransportDriversSave, RequestTransportDriversDeleteList, RequestBasicPersonRecognize, RequestTrailerPhone } from "@/api/path/index.js";
import { ElMessage } from 'element-plus'
import { Edit } from "@element-plus/icons-vue";
import upload from '@/components/uploadFile/upload.vue'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { computed, ref, watch } from 'vue';
import useAuthorize from "@/hooks/authorize";
import { findIndex } from "lodash-es";
import { validateIDCard } from '@/utils/index'
let roleList = useAuthorize()
const tableData = ref<any>([])
const centerDialogVisible = ref<any>(false)
const editcenterDialogVisible = ref<any>(false)
const transportDriversImg = ref<any>([])
const transportBase64 = ref<string[]>([])
const driverIdCardImg = ref<any>('')


/* *********************************** 分页获取数据 *********************************** */
const total = ref<any>(2)
const currentPage = ref<any>(1)
const pageSize = ref<any>(10)
const switchStatus = ref<any>(0)

const getData = () => {
    RequestTransportDriversGetlistlimit({
        page: currentPage.value,
        rows: pageSize.value,
        employee: JSON.parse(localStorage.getItem('roleInfo') as string)
    }).then((res: any) => {
        tableData.value = res.resultObj.data
        total.value = res.resultObj.total
    })
}
getData()
const handleSizeChange = (val: number) => {
    getData()
}
const handleCurrentChange = (val: number) => {
    getData()
}
/*  *********************************** 添加司机 *********************************** */
const ruleFormRef = ref<FormInstance>()
const addTableData = ref<any>({
    phone: '',
    name: '',
    password: '',
    identityCard: '',
    gender: ''
})
interface RuleForm {
    name: string,
    phone: number,
    identityCard: string,
    gender: string
    licenseNumber?: string,
    limit?: number,
}
//手机号校验自定义规则
const validatePhone = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入司机账号'))
    } else {
        // 验证手机号格式
        let regex = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[13589]))\d{8}$/
        if (!regex.test(value)) {
            callback(new Error('请输入正确的手机号'))
        } else {
            // RequestTrailerPhone(value).then((res: any) => {
            //     if (res.resultObj === true) {
            //         callback(new Error('手机号已存在'))
            //     } else {
            //         callback()
            //     }
            // })
            callback()
        }

    }
}
//身份证号校验自定义规则
const validateIdentityCard = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入身份证号'))
    } else {
        // 验证身份证号格式
        // let regex = /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/;
        // if (!regex.test(value)) {
        //     callback(new Error('请输入正确的身份证号'))
        // }
        if (!validateIDCard(value)) {
            callback(new Error('请输入正确的身份证号'))
        }
        callback()
    }
}
const validateGender = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入性别'))
    } else {
        if (value === '男' || value == '女') {
            callback()
        } else {
            callback(new Error('请输入正确的性别'))
        }
    }
}

const rules = ref<FormRules<RuleForm>>({
    name: {
        required: true,
        message: '请输入司机姓名',
        trigger: 'blur'

    },
    identityCard: {
        required: true,
        validator: validateIdentityCard,
        trigger: 'blur'
    },
    gender: {
        required: true,
        validator: validateGender,
        trigger: 'blur'
    },
    phone: {
        required: true,
        trigger: 'blur',
        validator: validatePhone
    },

})

/* 身份证 */
const Identification = ref<any>()
const IdentificationCard = (file: any) => {
    Identification.value = file.raw
    let BasicPersonRecognizeF = new FormData()
    BasicPersonRecognizeF.append('personCard', file.raw)
    RequestBasicPersonRecognize(BasicPersonRecognizeF).then((res: any) => {
        addTableData.value.identityCard = JSON.parse(res.resultObj).words_result.公民身份号码.words
        addTableData.value.name = JSON.parse(res.resultObj).words_result.姓名.words
        addTableData.value.gender = JSON.parse(res.resultObj).words_result.性别.words
    })
}
/* 驾照 */
const licenseNumber = ref<any>()
const licenseNumberCard = (file: any) => {
    licenseNumber.value = file.raw
    let drivingLicenseF = new FormData()
    drivingLicenseF.append('drivingLicense', file.raw)
    RequestBasicDrivingLicense(drivingLicenseF).then((res: any) => {
        addTableData.value.limit = JSON.parse(res.resultObj).words_result.至.words
        addTableData.value.licenseNumber = JSON.parse(res.resultObj).words_result.档案编号.words
    })
}
function fileToBase64(file: Blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve((<string>reader.result).split(',')[1]);
        reader.onerror = (error) => reject(error);
    });
}
const addDriverBtn = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let addDriverInfo = {
                transportDrivers: addTableData.value,
                driverIdCard: transportBase64.value,
                driveLicense: driverIdCardImg.value
            }
            addTableData.value.companyNode = JSON.parse(localStorage.getItem('roleInfo') as string).company
            RequestAddDriver(addDriverInfo).then((res: any) => {
                if (res.code == 0) {
                    centerDialogVisible.value = false
                    ElMessage.success(res.msg)
                    //其它处理代码
                    getData()
                }
            })
                .catch((err: any) => {
                    ElMessage.error(err)
                })
        } else {
            console.log(valid)
        }
    })
}



/*  *********************************** 查看 *********************************** */
const identityCardImg = ref<any>([])    //身份证
const licenseNumberImg = ref<any>('')   //行驶证
const srcList = ref<any>([])
const checkTableData = ref<any>({})
const check = (row: any) => {
    console.log(row)
    identityCardImg.value = []
    licenseNumberImg.value = ''
    srcList.value = []
    row.imgs.forEach((item: any) => {
        if (item.imageType == 0) {
            identityCardImg.value.push(item)
            srcList.value.push(item.url)
        } else {
            licenseNumberImg.value = item.url
            // srcList.value.push(item.url)
        }

    });
    switchStatus.value = row.status
    checkTableData.value = row
    editcenterDialogVisible.value = true
}
/*  *********************************** 删除&批量删除 *********************************** */
const ids = ref<any>([])
const delBtn = (row: any) => {
    ids.value.push(row.id)
    const idsFormData = new FormData()
    idsFormData.append('ids', ids.value)
    RequestTransportDriversDeleteList(idsFormData).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.msg)
            getData()
            ids.value = []
        } else {
            ElMessage.error(res.msg)
        }
    })
}
const handleSelectionChange = (val: any) => {
    val.forEach((item: any) => {
        ids.value.push(item.id)
    });
}



const hanldeIdCarImg = async (file: any, flagKey: string) => {
    if (flagKey === 'remove') {
        let index = transportDriversImg.value.findIndex(item => item.uid === file.uid)
        transportDriversImg.value.splice(index, 1)
    } else {
        transportDriversImg.value.push(file)
    }
}
watch(transportDriversImg.value, () => {
    if (transportDriversImg.value.length == 2) {
        transportDriversImg.value.forEach(async (element: any) => {
            transportBase64.value.push(await fileToBase64(element.raw));
        })
    }
})
const hanldeElectronIdCarImg = async (fileList: any, flagKey: string) => {
    if (flagKey === 'remove') return driverIdCardImg.value = ''
    driverIdCardImg.value = await fileToBase64(fileList.raw)
}
const handleStatusChange = (raw: any) => {
    if (raw.status == 3) return
    RequestChangeDriverStatus(raw.id).then((res: any) => {
        if (res.success) {
            ElMessage.success(res.msg)
        }
    })
}



</script>

<style scoped lang="scss">
.main {
    width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
    .top {
        width: 100%;
        background-color: #fff;
    }

    .content {
        width: 100%;
        background-color: #fff;
    }
}

.icon_i {
    position: absolute;
    top: 0;
    bottom: 0;
    left: -6.875rem;
    right: 0;
    margin: auto 0;
}

.downLoad {
    line-height: 1rem;
    margin-left: 0.625rem;
    color: #116cf8;
}

.el-select {
    width: 100%;
}

.el-input-number {
    width: 100%;
}

.drawer_top {
    width: 100%;
    background-color: #fff;
    border-radius: 0.5rem;
}

/* 弹出框样式 */
::v-deep .el-overlay {
    .el-dialog__header {
        background-color: #116cf8;
        margin-right: 0;
    }

    .el-dialog__title {
        color: #fff;
    }

    .dialog {
        .el-icon svg {
            color: #fff;
        }
    }

    .el-button {
        .el-icon svg {
            color: #116cf8;
        }
    }

    .el-form {
        .el-icon svg {
            color: #dcdfe6;
        }
    }
}

::v-deep .el-drawer {
    .el-overlay .el-icon svg {
        color: red;
    }

    .el-drawer__header {
        margin-bottom: 0;
    }
}

.DocumentNumber {
    .el-button {
        background-color: #fff;
        border: 0.0625rem solid #dcdfe6;
        border-left: none;
    }
}

.drawer_bottom {
    width: 100%;
    height: 10%;
    background-color: #fff;
    padding: 1.25rem;
    position: absolute;
    bottom: 0;
    right: 0;
}

.addTable {
    width: 100%;
    text-align: center;
    height: 2.5rem;
    line-height: 2.5rem;
    background-color: #e7f0fe;
    border: 0.0625rem dotted #116CF8;
    margin-top: 0.375rem;
    color: #116CF8;
    user-select: none;
    cursor: pointer;
}
</style>
